package com.example.demo6.controller;

import com.example.demo6.domain.Actor;
import com.example.demo6.domain.Movie;
import com.example.demo6.domain.Role;
import com.example.demo6.repository.MovieRepository;
import com.example.demo6.repository.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;


@Controller
@RequestMapping(value = "/role")
public class RoleController {
    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private MovieRepository movieRepository;


    @RequestMapping(value = {"/add/{id}"}, method = RequestMethod.GET)
    public String toAdd(Model model, @PathVariable Long id) {
        Movie movie = movieRepository.findOne(id);
        model.addAttribute("movie", movie);
        return "/role/add";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String doAdd(@RequestParam String roleName, @RequestParam String actorName, @RequestParam Long id) {
        Actor actor = new Actor();
        actor.setName(actorName);
        Movie movie = movieRepository.findOne(id);
        movie.addRole(actor, roleName);
        movieRepository.save(movie);
        return "redirect:/movie/detail/" + movie.getId();
    }


    @RequestMapping(value = {"edit/{id}"}, method = RequestMethod.GET)
    public String toEditRole(Model model, @PathVariable Long id) {
        Role role = roleRepository.findOne(id);
        model.addAttribute("role", role);
        return "role/edit";
    }


    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public String doEditRole(@RequestParam String roleName, @RequestParam String actorName, @RequestParam Long id) {
        Role role = roleRepository.findOne(id);
        role.setName(roleName);
        role.getActor().setName(actorName);
        roleRepository.save(role);
        return "redirect:/movie/detail/" + role.getMovie().getId();
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public String deleteRole(Model model, @PathVariable Long id) {
        Role role = roleRepository.findOne(id);
        roleRepository.delete(role);
        return "redirect:/movie/detail/" + role.getMovie().getId();
    }
}
